package database

import (
	"strconv"
	"time"

	sgjwt "gitee.com/salmon-go/common/jwt"

	"github.com/gin-gonic/gin"
)

//TableBase 包含基础字段
type TableBase struct {
	ID        int64  `json:"id,string" db:"id"`
	CreatorID int64  `json:"creator_id" db:"creator_id"`
	Creator   string `json:"creator" db:"creator"`
	CreatorIP string `json:"creator_ip" db:"creator_ip"`
	CreatedAt string `json:"created_at" db:"created_at"`
	UpdaterID int64  `json:"updater_id" db:"updater_id" gorm:"default:NULL"`
	Updater   string `json:"updater" db:"updater" gorm:"default:NULL"`
	UpdaterIP string `json:"updater_ip" db:"updater_ip" gorm:"default:NULL"`
	UpdatedAt string `json:"updated_at" db:"updated_at" gorm:"default:NULL"`
	DeleteTag int    `json:"delete_tag" db:"delete_tag" gorm:"default:0"`
}

var (
	//新建时要操作的字段
	CreateColumns = []string{"creator_id", "creator", "creator_ip", "created_at"}
	//更新时要操作的字段
	UpdateColumns = []string{"updater_id", "updater", "updater_ip", "updated_at"}
	//删除时要操作得字段
	DeleteColumns = append(UpdateColumns, "delete_tag")
)

// func (t *TableBase) TableName() string {
// 	return
// }

//Create ...
func (t *TableBase) SetCreateColumn(c *gin.Context) {
	t.ID = NewSnowflake(1).Generate()
	userID := c.Request.Header.Get(sgjwt.KeyTokenClaim)
	t.CreatorID, _ = strconv.ParseInt(userID, 10, 64)
	t.CreatorIP = c.ClientIP()
	t.CreatedAt = time.Now().String()[0:19]
}

//Modify ...
func (t *TableBase) SetUpdateColumn(c *gin.Context) {
	userID := c.Request.Header.Get(sgjwt.KeyTokenClaim)
	t.UpdaterID, _ = strconv.ParseInt(userID, 10, 64)
	t.UpdaterIP = c.ClientIP()
	t.UpdatedAt = time.Now().String()[0:19]
}
